package com.imooc.service.impl;

import com.imooc.mapper.UserAddressMapper;
import com.imooc.pojo.UserAddress;
import com.imooc.pojo.bo.AddressBO;
import com.imooc.service.AddressService;
import imooc.enums.YesOrNo;
import org.n3r.idworker.Sid;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * @author cg.hu
 * @version 1.0.0
 * @date 2021/1/28 14:48
 * @description
 * @since 1.0.0
 */
@Service
public class AddressServiceImpl implements AddressService {

    final static Logger logger = LoggerFactory.getLogger(AddressServiceImpl.class);

    @Autowired
    private UserAddressMapper userAddressMapper;

    @Autowired
    private Sid sid;

    /**
     * @author cg.hu
     * @version 2.6
     * @date 2021/1/28 14:59
     * @description  根据用户ID，查询收货地址列表
     **/
    @Override
    @Transactional(propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
    public List<UserAddress> queryAll(String userId) throws Exception{
        UserAddress userAddress = new UserAddress();
        userAddress.setUserId(userId);
        return userAddressMapper.select(userAddress);
    }

    /**
     * @author cg.hu
     * @version 2.6
     * @date 2021/1/28 15:38
     * @description    添加地址
     **/
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void addNewUserAddress(AddressBO addressBO) throws Exception {
        // 1,判断当前用户是否存在地址，如果没有则新增为默认地址
        Integer isDefault = 0;
        List<UserAddress> userAddressList = this.queryAll(addressBO.getUserId());
        if (CollectionUtils.isEmpty(userAddressList)) {
            isDefault = 1;
        }
        UserAddress userAddress = new UserAddress();
        BeanUtils.copyProperties(addressBO,userAddress);
        // 2，保存地址到数据库
        String addressId = sid.nextShort();
        userAddress.setId(addressId);
        userAddress.setIsDefault(isDefault);
        userAddress.setCreatedTime(new Date());
        userAddress.setUpdatedTime(new Date());
        int effectedRows = userAddressMapper.insert(userAddress);
        if (effectedRows <= 0) {
            throw new Exception("添加地址失败");
        }
    }

    /**
     * @author cg.hu
     * @version 2.6
     * @date 2021/1/28 16:22
     * @description    修改地址
     **/
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void updateNewUserAddress(AddressBO addressBO) throws Exception {
        String addressId = addressBO.getAddressId();
        UserAddress userAddress = new UserAddress();
        BeanUtils.copyProperties(addressBO, userAddress);
        userAddress.setId(addressId);
        userAddress.setUpdatedTime(new Date());
        int effectedRows = userAddressMapper.updateByPrimaryKeySelective(userAddress);
        if (effectedRows <= 0) {
            throw new Exception("修改地址失败");
        }
    }

    /**
     * @author cg.hu
     * @version 2.6
     * @date 2021/1/28 16:45
     * @description    根据用户ID，地址ID，删除对应的地址信息
     **/
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void deleteNewUserAddress(String userId, String addressId) throws Exception {
        UserAddress userAddress = new UserAddress();
        userAddress.setUserId(userId);
        userAddress.setId(addressId);
        int effectedRows = userAddressMapper.delete(userAddress);
        if (effectedRows <= 0) {
            throw new Exception("删除地址失败");
        }
    }

    /**
     * @author cg.hu
     * @version 2.6
     * @date 2021/1/28 17:24
     * @description    设置默认地址
     **/
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void updateUserAddressToBeDefault(String userId, String addressId) throws Exception {
        // 1. 查找默认地址，设置为不默认

        UserAddress userAddress = new UserAddress();
        userAddress.setUserId(userId);
        userAddress.setIsDefault(YesOrNo.YES.type);
        List<UserAddress> userAddressList = userAddressMapper.select(userAddress);
        for (UserAddress address : userAddressList) {
            address.setIsDefault(YesOrNo.NO.type);
            userAddressMapper.updateByPrimaryKeySelective(address);
        }

        // 2. 根据地址ID，修改为默认
        UserAddress defaultAddress = new UserAddress();
        defaultAddress.setId(addressId);
        defaultAddress.setUserId(userId);
        defaultAddress.setIsDefault(YesOrNo.YES.type);
        defaultAddress.setUpdatedTime(new Date());

        int effectedRows = userAddressMapper.updateByPrimaryKeySelective(defaultAddress);
        if (effectedRows <= 0) {
            throw new Exception("删除地址失败");
        }
    }

    /**
     * 根据用户ID, 地址ID查询地址
     * */
    @Transactional(propagation = Propagation.SUPPORTS, rollbackFor = {Exception.class})
    @Override
    public UserAddress queryUserAddress(String userId, String addressId) throws Exception {
        UserAddress singleAddress = new UserAddress();
        singleAddress.setUserId(userId);
        singleAddress.setId(addressId);
        return userAddressMapper.selectOne(singleAddress);
    }
}
